package com.example.fence.init;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.fence.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;



@Component
@Slf4j
public class DeviceUtil {
    //SN码与设备ID映射表
    public static Map<String ,String > SNtoUUID= new HashMap<>();
    @Value("${auth.username}")
    private String username;
    @Value("${auth.password}")
    private String password;

    /**
     * 项目启动时启动，获取设备列表，建立映射表
     */
    @PostConstruct
    public void start() {
        init();
    }
    public static void init() {
        int pageSize=100000;
        //  int pageSize=10;
        String token= HttpClientUtil.get_token("http://47.92.164.101:28080/api/auth/login","tenant@thingsboard.org","tenant")[0];
        String refreshToken=HttpClientUtil.get_token("http://47.92.164.101:28080/api/auth/login","tenant@thingsboard.org","tenant")[1];
        //应该还要判断无法获取到设备列表怎么办
        String url="http://47.92.164.101:28080/api/tenant/deviceInfos?pageSize="+pageSize+"&page=0&type=电池包";
        String[] resultStr=HttpClientUtil.get_data(url,token);//String 格式获取结果, [0]为statusCode，[1]为结果(结果可能不是json)
        if(Integer.valueOf(resultStr[0])==200){
            //获取设备列表
            JSONObject jsonResult = JSONObject.parseObject(resultStr[1]);
            JSONArray dataList=jsonResult.getJSONArray("data");
            //遍历提取id和name存到map里
            for(int i=0;i<dataList.size();i++){
                if(!SNtoUUID.containsKey(dataList.getJSONObject(i).get("name").toString())){
                    SNtoUUID.put(dataList.getJSONObject(i).get("name").toString(), dataList.getJSONObject(i).getJSONObject("id").get("id").toString());
                }

            }

            for (String key : SNtoUUID.keySet()) {
                System.out.println(key);
            }
            // 打印值集合
            for (String value : SNtoUUID.values()) {
                System.out.println(value);
            }
            log.info("Device init success");
            // SNtoUUID.put("860987051027073","d11522a0-1952-11ee-8bf7-791789e1e577");

        }
        else{
            log.info("SNtoUUID error"+Integer.valueOf(resultStr[0]));
        }
    }
}
